import React, { useState, useRef, useEffect } from 'react';
import {
  ModalForm,
  ProForm,
  ProFormSelect,
  ProFormText,
  ProFormDatePicker,
  ProFormGroup,
  ProFormList,
  ProFormDependency,
  ProTable,
  ProFormTextArea,
  ProFormRate,
} from '@ant-design/pro-components';
import { Button, Tag, message, Upload, Space, Modal, notification } from 'antd';
import {
  PlusOutlined,
  SyncOutlined,
  CheckCircleOutlined,
  ClockCircleOutlined,
  LoadingOutlined,
  ExclamationCircleOutlined,
} from '@ant-design/icons';

import type { ProFormInstance } from '@ant-design/pro-components';
import type { UploadProps } from 'antd';

import { useRequest } from 'umi';
import moment from 'moment';

const { confirm } = Modal;

const waitTime = (time: number = 100) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(true);
    }, time);
  });
};

const WeekPlan = ({ stageId, tabKey, refreshBadge }: any) => {
  const editWeekPlanRef = useRef<ProFormInstance>();

  //学生端——获取自己的周计划列表
  const getMyWeekPlan = useRequest(
    () => {
      return {
        url: `http://10.1.40.84:9998/stuTrain/getMyWeekPlan?stageId=${stageId}`,
        method: 'GET',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
      };
    },
    {
      manual: true,
    },
  );

  //共通端——查看一个周计划详细
  const getOneWeekPlanState = useRequest(
    (id = null) => {
      return {
        url: `http://10.1.40.84:9998/stuTrain/getOneWeekPlanState?id=${id}`,
        method: 'GET',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
      };
    },
    {
      manual: true,
    },
  );

  //修改周计划
  const updateWeekPlan = useRequest(
    (data = {}) => {
      return {
        url: `http://10.1.40.84:9998/stuTrain/updateWeekPlan`,
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
    {
      manual: true,
      onSuccess: () => {
        getMyWeekPlan.run();
        refreshBadge();
      },
    },
  );
  //修改周计划状态
  const updateWeekPlanState = useRequest(
    (id = null, state = null) => {
      return {
        url: `http://10.1.40.84:9998/stuTrain/updateWeekPlanState?id=${id}&state=${state}`,
        method: 'GET',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
      };
    },
    {
      manual: true,
      onSuccess: () => {
        getMyWeekPlan.run();
        refreshBadge();
      },
    },
  );

  // 上传材料文件
  const props: UploadProps = {
    name: 'material',
    action: 'http://10.1.40.84:9998/stuTrain/uploadMaterial',
    headers: {
      Authorization: localStorage.getItem('token') || '',
    },
    maxCount: 1,
    // showUploadList: false,
  };
  //忽略 周计划
  const showDeleteConfirm = (record: any) => {
    confirm({
      title: '确定忽略该周计划吗?',
      icon: <ExclamationCircleOutlined />,
      content: '忽略周计划后将不能编辑周计划',
      okText: '忽略',
      okType: 'danger',
      cancelText: '取消',
      onOk() {
        // console.log('OK');
        updateWeekPlanState.run(record.id, '忽略');
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  };
  //确认 周计划
  const showConfirm = (record: any) => {
    confirm({
      title: '确认接收该周计划吗?',
      icon: <ExclamationCircleOutlined />,
      content: '确认周计划后请尽快完成',
      okText: '确认',
      okType: 'danger',
      cancelText: '取消',
      onOk() {
        updateWeekPlanState.run(record.id, '进行中');
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  };

  //
  useEffect(() => {
    getMyWeekPlan.run();
  }, [stageId]);

  const weekPlanColumns = [
    {
      title: '学生',
      dataIndex: 'stuName',
      key: 'stuName',
    },
    {
      title: '周计划名称',
      dataIndex: 'weekPlanName',
      key: 'weekPlanName',
    },
    {
      title: '所属阶段',
      dataIndex: 'stageName',
      key: 'stageName',
      render: (text: any) => <Tag color={'blue'}>{text}</Tag>,
    },
    {
      title: '周计划状态',
      dataIndex: 'weekPlanState',
      key: 'weekPlanState',
      render: (text: any) => {
        if (text === '未接收' || text === '忽略') {
          return (
            <Tag icon={<ClockCircleOutlined />} color="default">
              {text}
            </Tag>
          );
        } else if (text === '进行中') {
          return (
            <Tag icon={<SyncOutlined spin />} color={'processing'}>
              {text}
            </Tag>
          );
        } else {
          return (
            <Tag icon={<CheckCircleOutlined />} color="success">
              {text}
            </Tag>
          );
        }
      },
    },
    {
      title: '组长',
      dataIndex: 'seniorName',
      key: 'seniorName',
    },
    {
      title: '导师',
      dataIndex: 'teaName',
      key: 'teaName',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      render: (text: any) => moment(text).format('YYYY-MM-DD'),
    },
    {
      title: '操作',
      key: 'option',
      align: 'center',
      render: (text: any, record: any) => (
        <Space>
          <ModalForm
            key="1"
            title={'查看周计划'}
            trigger={
              <a
                onClick={() => {
                  getOneWeekPlanState.run(record?.id).then((e) => {
                    console.log(e);
                    editWeekPlanRef.current?.setFieldsValue(e);
                  });
                }}
              >
                查看
              </a>
            }
            autoFocusFirstInput
            modalProps={{
              onCancel: () => console.log('run'),
              destroyOnClose: true,
            }}
            submitTimeout={2000}
            onFinish={async (values) => {
              await waitTime(2000);
              console.log(values);
              updateWeekPlan.run(values);
              message.success('提交成功');
              return true;
            }}
            formRef={editWeekPlanRef}
          >
            <ProForm.Group>
              <ProFormText width="sm" name="id" hidden />
              <ProFormText width="sm" name="seniorId" hidden />
              <ProFormText width="sm" name="stageId" hidden />
              <ProFormText width="sm" name="studentId" hidden />
              <ProFormText width="sm" name="teacherId" hidden />
              <ProFormText
                width={'md'}
                name="weekPlanName"
                label="周计划名称"
              />

              <ProFormSelect
                width={'md'}
                name="weekPlanState"
                label="周计划状态"
                valueEnum={{
                  未接收: '未接收',
                  忽略: '忽略',
                  进行中: '进行中',
                  已完成: '已完成',
                  负责人已审核: '负责人已审核',
                  导师已阅: '导师已阅',
                }}
              />

              {/* <ProFormText width={"md"} name="weekPlanState" label="周计划状态" disabled={tabKey === "3"} /> */}
              <ProFormText width={'md'} name="personTarget" label="个人目标" />
              <ProFormText
                width={'md'}
                name="teaTarget"
                label="导师规划目标"
                disabled
              />
              <ProFormTextArea
                width={'md'}
                name="personEvaluate"
                label="个人评价"
                fieldProps={{
                  rows: 3,
                }}
                disabled={tabKey === '3'}
              />
              <ProFormTextArea
                width="md"
                name="teaEvaluate"
                label="导师评价"
                disabled
                fieldProps={{
                  rows: 3,
                }}
              />
              <ProFormDatePicker
                width={'md'}
                name="createTime"
                label="创建时间"
                disabled
              />
              <ProFormRate
                readonly
                width="md"
                name="teaScore"
                label="导师评分"
              />
            </ProForm.Group>
            <ProFormList
              name="materialList"
              label="材料信息"
              // rules={[
              //   {
              //     validator: async (_, value) => {
              //       // console.log(value);
              //       if (value && value.length > 0) {
              //         return;
              //       }
              //       throw new Error('至少要有一项！');
              //     },
              //   },
              // ]}
              creatorButtonProps={{
                creatorButtonText: '添加材料',
                hidden: tabKey === '3',
              }}
              copyIconProps={tabKey === '3' ? false : { tooltipText: '复制' }}
              deleteIconProps={tabKey === '3' ? false : { tooltipText: '删除' }}
            >
              {(meta: any, index: any, action: any, count: any) => {
                return (
                  <ProFormGroup key="group">
                    <ProFormText
                      width="sm"
                      required
                      name="materialName"
                      label="材料名称"
                      disabled={tabKey === '3'}
                    />
                    <ProFormSelect
                      label="材料类型"
                      name="materialType"
                      width="xs"
                      required
                      disabled={tabKey === '3'}
                      valueEnum={{
                        学习报告: '学习报告',
                        参考文献: '参考文献',
                      }}
                    />
                    <ProFormDependency name={['materialType']}>
                      {({ materialType }) => {
                        if (materialType === '参考文献') {
                          return (
                            <ProFormText
                              width="sm"
                              name="materialContent"
                              label="文献链接"
                              required
                            />
                          );
                        } else if (
                          materialType === '学习报告' ||
                          materialType === '阶段性报告'
                        ) {
                          return (
                            <>
                              <Upload
                                {...props}
                                onChange={(info) => {
                                  if (info.file.status === 'done') {
                                    action.setCurrentRowData({
                                      materialContent: info.file.response.data,
                                    });
                                    message.success(
                                      `${info.file.name} 上传成功！`,
                                    );
                                  } else if (info.file.status === 'error') {
                                    message.error(
                                      `${info.file.name} file upload failed.`,
                                    );
                                  }
                                }}
                              >
                                <Button
                                  type="link"
                                  style={
                                    index === 0
                                      ? { marginTop: 30 }
                                      : { marginTop: 0 }
                                  }
                                  disabled={tabKey === '3'}
                                >
                                  上传材料
                                </Button>
                              </Upload>

                              <ProFormText
                                width="sm"
                                name="materialContent"
                                required
                                hidden
                              />
                            </>
                          );
                        } else {
                          return null;
                        }
                      }}
                    </ProFormDependency>
                    <ProFormDependency name={['materialType']}>
                      {({ materialType }) => {
                        if (
                          materialType === '学习报告' &&
                          action.getCurrentRowData().materialContent
                        ) {
                          return (
                            <Button
                              type={'link'}
                              style={
                                index === 0
                                  ? { marginTop: 30 }
                                  : { marginTop: 0 }
                              }
                              onClick={() => {
                                window.open(
                                  action.getCurrentRowData().materialContent,
                                );
                              }}
                            >
                              下载
                            </Button>
                          );
                        } else {
                          return null;
                        }
                      }}
                    </ProFormDependency>
                  </ProFormGroup>
                );
              }}
            </ProFormList>
          </ModalForm>
          {tabKey === '3' ? null : (
            <a key="22" onClick={() => showConfirm(record)}>
              确认接收
            </a>
          )}
          {tabKey === '3' ? null : (
            <a key="2" onClick={() => showDeleteConfirm(record)}>
              忽略
            </a>
          )}
        </Space>
      ),
    },
  ];

  return (
    <ProTable
      columns={weekPlanColumns}
      // cardBordered
      dataSource={getMyWeekPlan?.data || []}
      rowKey="id"
      search={false}
      pagination={{
        pageSize: 5,
        hideOnSinglePage: true,
      }}
      options={false}
      dateFormatter="string"
    />
  );
};

export default WeekPlan;
